package practice.tmp;

import java.util.HashSet;

public class Solution1319 {
    int[] father;

    public int makeConnected(int n, int[][] connections) {
        int count = n;
        int extra = 0;
        father = new int[n];
        for (int i = 0; i < n; i++) {
            father[i] = i;
        }
        for (int[] x : connections) {
            if (same(x[0], x[1])) extra++;
            else {
                join(x[0], x[1]);
                count--;
            }
        }
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < n; i++) {
            if (!set.contains(father[i])) set.add(father[i]);
        }
        count = set.size();
        if (extra < count - 1) return -1;
        return count - 1;
    }

    public int find(int x) {
        if (x == father[x]) return x;
        father[x] = find(father[x]);
        return father[x];
    }

    public boolean same(int x, int y) {
        x = find(x);
        y = find(y);
        return x == y;
    }

    public void join(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        father[y] = x;
    }
}
